
var ws = new WebSocket('wss://' + location.host + '/call'); //websockt连接后台
var videoInput//视频输入流   自己画像
var videoOutput;//视频输出流  好友画像
var webRtcPeer;//视频流就是靠这个东西传输的
var response;
var callerMessage;
var from;

var registerName = null;//注册名字  注册状态
var registerState = null;
const NOT_REGISTERED = 0;
const REGISTERING = 1;
const REGISTERED = 2;



//注册
function register() {
    // var name = document.getElementById('name').value;
    var name = 'ff';
    if (name == '') {
        window.alert('You must insert your user name');
        return;
    }

    var message = {
        id : 'register',
        name : name
    };
    sendMessage(message);
}


//呼叫对方
function call() {


    var options = {
        localVideo : videoInput, //本地流，
        remoteVideo : videoOutput, //好友流
        onicecandidate : onIceCandidate,
        onerror : onError
    }
    webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
        function(error) {
            if (error) {
                return console.error(error);
            }
            webRtcPeer.generateOffer(onOfferCall);
        });
}

function onOfferCall(error, offerSdp) {
    if (error)
        return console.error('Error generating the offer');
    console.log('Invoking SDP offer callback function');
    var message = {
        id : 'call',
        from : 'ff',
        to : 'cc',
        sdpOffer : offerSdp
    };
    sendMessage(message);
}


//被人呼叫
function incomingCall(message) {//有人呼叫

    // //显示呼叫界面
    // var div_person_video_invite = document.getElementById('div_person_video_invite');
    // div_person_video_invite.style.display = 'block';
    //
    //
    //

        from = message.from;

}



function onError() {
    console.error('错误');
}


//ws接收服务器来的消息
ws.onmessage = function(message) { //websockt 接收服务器的消息
    var parsedMessage = JSON.parse(message.data);
    console.info('Received message: ' + message.data);

    switch (parsedMessage.id) {
        case 'resgisterResponse': //注册response
            resgisterResponse(parsedMessage);
            break;
        case 'callResponse': //呼叫response
            callResponse(parsedMessage);
            break;
        case 'incomingCall': //有人呼叫进来
            incomingCall(parsedMessage);
            break;
        case 'startCommunication': //视频通话开始
            startCommunication(parsedMessage);
            break;
        case 'stopCommunication': //视频通话结束
            console.info('Communication ended by remote peer');
            stop(true);
            break;
        case 'iceCandidate'://视频流传输
            webRtcPeer.addIceCandidate(parsedMessage.candidate, function(error) {
                if (error)
                    return console.error('Error adding candidate: ' + error);
            });
            break;
        default:
            console.error('Unrecognized message', parsedMessage);
    }
}

function resgisterResponse(message) {
    if (message.response == 'accepted') {
    } else {
        var errorMessage = message.message ? message.message
            : 'Unknown reason for register rejection.';
        console.log(errorMessage);
        alert('Error registering user. See console for further information.');
    }
}

function callResponse(message) {
    if (message.response != 'accepted') {
        console.info('Call not accepted by peer. Closing call');
        var errorMessage = message.message ? message.message
            : 'Unknown reason for call rejection.';
        console.log(errorMessage);
        stop();
    } else {
        setCallState(IN_CALL);
        webRtcPeer.processAnswer(message.sdpAnswer, function(error) {
            if (error)
                return console.error(error);
        });
    }
}



//开始通话
function startCommunication(message) {
    // setCallState(IN_CALL);
    webRtcPeer.processAnswer(message.sdpAnswer, function(error) {
        if (error)
            return console.error(error);
    });
}





var callState = null;
const NO_CALL = 0;
const PROCESSING_CALL = 1;
const IN_CALL = 2;

window.onload = function() {
    console = new Console();
    videoInput = document.getElementById('videoInput');
    videoOutput = document.getElementById('videoOutput');

    setTimeout('register()', 5000);

}

window.onbeforeunload = function() {
    ws.close();
}






function stop(message) {
    //setCallState(NO_CALL);
    if (webRtcPeer) {
        webRtcPeer.dispose();
        webRtcPeer = null;

        if (!message) {
            var message = {
                id : 'stop'
            }
            sendMessage(message);
        }
    }
}


function onIceCandidate(candidate) {
    console.log("Local candidate" + JSON.stringify(candidate));

    var message = {
        id : 'onIceCandidate',
        candidate : candidate
    };
    sendMessage(message);
}

function sendMessage(message) {
    var jsonMessage = JSON.stringify(message);
    console.log('Senging message: ' + jsonMessage);
    ws.send(jsonMessage);
}

//拒绝个人视频通话
function personVideoRefuse() {

}

//个人视频转语音
function personVideoVoice() {
   //隐藏界面
    //显示界面
}

//接听个人视频通话
function personVideoAnswer() {
    //隐藏界面
    var div_person_video_invite = document.getElementById('div_person_video_invite');
    div_person_video_invite.style.display = 'none'
    //显示界面
    var div_person_video_chat = document.getElementById('div_person_video_chat');
    div_person_video_chat.style.display = 'block'

    var options = {
        localVideo : videoInput,
        remoteVideo : videoOutput,
        onicecandidate : onIceCandidate,
        onerror : onError
    }
    webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
        function(error) {
            if (error) {
                return console.error(error);
            }
            webRtcPeer.generateOffer(onOfferIncomingCall);
        });
}

//传输数据流
function onOfferIncomingCall(error, offerSdp) {
    if (error)
        return console.error("Error generating the offer");
    var response = {
        id : 'incomingCallResponse',
        from : from,
        callResponse : 'accept',
        sdpOffer : offerSdp
    };
    sendMessage(response);
}




